﻿using System;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Windows.Media;
using SilverChart.Core.Service;

namespace SilverChart.Core.Configuration.Converter {
    [ServiceProvider(LayzeCreation = true, Singleton = true)]
    public class ColorConverter : ConfigurationConverter<Color> {
        const String RGB_REGEX = @"(?<RGB>(?<R>[0-9a-fA-F])(?<G>[0-9a-fA-F])(?<B>[0-9a-fA-F]))";
        const String ARGB_REGEX = @"(?<ARGB>(?<A>[0-9a-fA-F])(?<R>[0-9a-fA-F])(?<G>[0-9a-fA-F])(?<B>[0-9a-fA-F]))";
        const String RRGGBB_REGEX = @"(?<RGB>(?<R>[0-9a-fA-F]{2})(?<G>[0-9a-fA-F]{2})(?<B>[0-9a-fA-F]{2}))";
        const String AARRGGBB_REGEX = @"(?<ARGB>(?<A>[0-9a-fA-F]{2})(?<R>[0-9a-fA-F]{2})(?<G>[0-9a-fA-F]{2})(?<B>[0-9a-fA-F]{2}))";

        public const Byte DEFAULT_COLOR_CHANNAL_VALUE = 255;

        public const String COLOR = @"#(" + RGB_REGEX + "|" + ARGB_REGEX + "|" + RRGGBB_REGEX + "|" + AARRGGBB_REGEX + ")";

        const String FULL_COLOR_REGEX = "^" + COLOR + "$";

        private static Regex Color_Regex_Object = new Regex(FULL_COLOR_REGEX);

        public bool Convert(string input, out Color value) {
            if (input != null && input.Trim().Length > 0) {
                Match match = Color_Regex_Object.Match(input);
                if (match.Success) {
                    Byte A, R, G, B;
                    A = DEFAULT_COLOR_CHANNAL_VALUE;
                    if (match.Groups["ARGB"].Success) {
                        A = GetByteFromHex(match.Groups["A"].Value);
                    }
                    R = GetByteFromHex(match.Groups["R"].Value);
                    G = GetByteFromHex(match.Groups["G"].Value);
                    B = GetByteFromHex(match.Groups["B"].Value);

                    value = Color.FromArgb(A, R, G, B);
                    return true;
                }
            }

            value = Colors.Black;
            return false;
        }

        private Byte GetByteFromHex(String hex) {
            return Byte.Parse(hex, NumberStyles.HexNumber);
        }
    }
}
